<template>
    <div class="input-box untouchable">
        <el-input v-model="inputValue" :type="type" :inputmode="inputMode" :maxlength="boxCount" class="box-input"
            ref="boxInputRef" @focus="focusInput = true" @blur="focusInput = false"
            @keydown.left.right.up.down.prevent />
        <div style="display: flex;justify-content: space-between;" @click="clickBox">
            <div :class="`box-self ${getClass(index)}`" :style="`background: ${color};`" v-for="(i, index) in box">
                {{ i }}
            </div>
        </div>
    </div>
</template>

<script setup>
const props = defineProps({
    modelValue: {
        type: String,
        default: ""
    },
    boxCount: {
        type: Number,
        default: 5
    },
    boxSize: {
        type: [String, Number],
        default: 30
    },
    color: {
        type: String,
        default: "#fff"
    },
    type: {
        type: String,
        default: "number"
    },
    inputMode: {
        type: String,
        default: "numeric"
    }
})

const getClass = (index) => {
    return !focusInput.value ? "" : index < inputValue.value.length ? 'active' : 'unactive'
}

const focusInput = ref(false)

const size = computed(() => {
    // 判断props.boxSize是否有px，没有则添加，有则直接返回
    return props.boxSize.toString().includes("px") ? props.boxSize : props.boxSize + "px"
})

const boxInputRef = ref(null)

const emit = defineEmits(["update:modelValue", "complete"])

const inputValue = ref(props.modelValue)

const box = computed(() => {
    inputValue.value = inputValue.value.slice(0, props.boxCount)
    return inputValue.value.toString().toUpperCase().padEnd(props.boxCount, " ").split("")
})

watch(inputValue, (newValue) => {
    emit("update:modelValue", newValue)
    if (newValue.length >= props.boxCount) {
        boxInputRef.value.blur()
        emit("complete")
    }
})
const clickBox = () => {
    boxInputRef.value.focus()
}
</script>

<style>
.box-self {
    width: v-bind(size) !important;
    display: flex !important;
    justify-content: center !important;
    align-items: center !important;
    font-size: 16px !important;
    border-radius: 3px;
    aspect-ratio: 1;
    transition: all .5s;
}

.box-input {
    width: 0 !important;
    height: 0 !important;
    opacity: 0 !important;
    position: absolute !important;
    pointer-events: none !important
}

.box-self.active {
    background: #71d171 !important;
}

.box-self.unactive {
    background: #ff6e6e !important;
}
</style>